package com.gyms.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.adapter.LocationListAdapter;
import com.gyms.base.BaseActivity;
import com.gyms.bean.SetLocationBean;
import com.gyms.manager.LocationManger;
import com.gyms.manager.TitleManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import constant.EventConstant;
import utils.StringUtils;
import weight.PhoneEditText;
import weight.UiEvent;

/**
 * 设置位置页面
 */
public class SetLocationActivity extends BaseActivity implements View.OnClickListener, LocationSource, AMapLocationListener,AMap.OnCameraChangeListener, PoiSearch.OnPoiSearchListener, TextView.OnEditorActionListener {

    private TextView mTvSure;
    private final static String S_CAN_CLICK_COLOR="#0396eb";
    private final static String S_NOT_CLICK_COLOR="#68C0F3";
    private boolean isCanSub;

    private MapView mMVSetLocation;
    private RecyclerView mRvLocationList;
    //初始化地图控制器对象
    private AMap aMap;
    //底部列表相关

    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;

    private LocationManger mLocationManger;
    private boolean isFirst=true;//默认第一次设置

    private TextView mTvReturn;
    //请求周边参数相关
    private static final String mPoiType="07|12|05";//

    private static final int mCurPage=1;//页码

    private static final int mSize=30;// 请求数量
    private static final int mRadius=5000;//周边半径
    //周边地图信息 数据源
    private ArrayList<SetLocationBean> mSetLocationBeans=new ArrayList<>();

    private LocationListAdapter mLocationListAdapter;
    private PhoneEditText mPtSearchLocation;
    private LatLng mCurLatLng;
    private AMapLocation aMapLocation;

    //空页面相关
    private ViewStub mVSEmptyView;
    //显示中心点图标
    private Marker mMarker;



    @Override
    protected int getLayoutResId() {
        return R.layout.activity_set_loaction;
    }

    @Override
    protected void initView() {
        initData();
        setTitle("设置位置");
        mTitleManager.setLeftCloseImg(R.drawable.close_selector);
        setBack();
        initRightView();
        findView();
        initLocationList();
    }

    private void initData() {
        mLocationManger=LocationManger.getInstance(mContext);
    }

    /**
     * 初始化地理位置列表
     */

    private void initLocationList() {
        mLocationListAdapter = new LocationListAdapter(mContext,mSetLocationBeans);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvLocationList.setLayoutManager(mLayoutManager);
        mRvLocationList.setAdapter(mLocationListAdapter );
    }

    /**
     * 初始化地图
     */

    private void initMapView() {
        if (aMap == null) {
            aMap = mMVSetLocation.getMap();
        }
    }

    @Override
    protected void setListener() {
        initMapView();
        showBluePoint();
        setSearchAction();
        mTvReturn.setOnClickListener(this);
        aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器
        setSubState();
    }

    /**
     * 设置搜索事件
     */

    private void setSearchAction() {
        mPtSearchLocation.setOnEditorActionListener(this);
        mPtSearchLocation.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mPtSearchLocation.setInputType(EditorInfo.TYPE_CLASS_TEXT);
    }

    /**
     * 实现定位蓝点
     */

    private void showBluePoint() {
        aMap.setLocationSource(this);
// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
// 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    @Override
    protected void processLogic() {
    }

    @Override
    protected void setTitleTheme() {
        mTheme = TitleManager.TitleTheme.White;
    }

    @Override
    public void needSavedInstanceState(Bundle savedInstanceState) {
        mMVSetLocation.onCreate(savedInstanceState);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_close_in, R.anim.activity_close_out);
    }

    private void initRightView() {
        mTvSure = mTitleManager.setRightText("确定");
        mTvSure.setTextColor(getResources().getColor(R.color.c_0396EB));
        mTvSure.setOnClickListener(this);
    }

    private void findView() {
        mMVSetLocation = (MapView) findViewById(R.id.mv_set_location);
        mRvLocationList = (RecyclerView) findViewById(R.id.rv_location_list);
        mTvReturn = (TextView) findViewById(R.id.tv_return);
        mPtSearchLocation = (PhoneEditText) findViewById(R.id.pt_search_location);
        mVSEmptyView= (ViewStub) findViewById(R.id.vs_empty_view);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right:
                if(null==mLocationListAdapter||!isCanSub){
                    ToastUtil.showToast(mContext,"当前地区不可选择");
                    return;
                }
                EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_SET_LOCATION,mLocationListAdapter.mSelectedBean));
                onBackPressed();
                break;

            case R.id.tv_return:
                LatLng mCurLatLng;
                if(null!=aMapLocation){
                    mCurLatLng=new LatLng(aMapLocation.getLatitude(),  aMapLocation.getLongitude());
                }else {
                    mCurLatLng=new LatLng(mLocationManger.latitude,mLocationManger.longitude);
                }
                changeCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(mCurLatLng, 17, 0, mSize)));
                break;
        }
    }

    /**
     * 根据动画按钮状态，调用函数animateCamera或moveCamera来改变可视区域
     */
    private void changeCamera(CameraUpdate update) {
            aMap.moveCamera(update);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMVSetLocation.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMVSetLocation.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMVSetLocation.onSaveInstanceState(outState);
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            AMapLocationClientOption locationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(locationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null&&aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                this.aMapLocation=aMapLocation;
            }
            if (isFirst) {
                isFirst = false;
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new com.amap.api.maps.model.LatLng(aMapLocation.getLatitude(),  aMapLocation.getLongitude()), 17));
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMVSetLocation.onDestroy();
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        mCurLatLng=cameraPosition.target;
        doSearchSound();
        doShowCenter();
    }

    /**
     * 展示中心点坐标
     */

    private void doShowCenter() {
        if(null!=mMarker){
            mMarker.setPosition(mCurLatLng);
            mMarker.setDraggable(false);
            return;
        }
        mMarker=aMap.addMarker(new MarkerOptions().position(mCurLatLng));
    }

    private void doSearchSound() {
        String keyWord = mPtSearchLocation.getText().toString();
        PoiSearch.Query query = new PoiSearch.Query(keyWord, mPoiType, "");

//keyWord表示搜索字符串，
//第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
//cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符s串，空字符串代表全国在全国范围内进行搜索
        query.setPageSize(mSize);// 设置每页最多返回多少条poiItem
        query.setPageNum(mCurPage);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(mContext, query);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(mCurLatLng.latitude,
                mCurLatLng.longitude), mRadius));//设置周边搜索的中心点以及半径

        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int code) {
        ArrayList<PoiItem> mPoiItems= poiResult.getPois();
        mSetLocationBeans.clear();
        if(StringUtils.isNull(mPoiItems)){
            isCanSub=false;
            setSubState();
            mLocationListAdapter.notifyDataSetChanged();
            isShowEmptyView(false);
            return;
        }
        isCanSub=true;
        isShowEmptyView(true);
        setSubState();
        for(int i=0;i<mPoiItems.size();i++){
            SetLocationBean mSetLocationBean=new SetLocationBean();
            mSetLocationBean.mPoiItem=mPoiItems.get(i);
            if(i==0){
                mSetLocationBean.isSelected=true;
                mLocationListAdapter.mSelectedBean=mSetLocationBean;
            }
            mSetLocationBeans.add(mSetLocationBean);
        }
        mLocationListAdapter.notifyDataSetChanged();
        mRvLocationList.smoothScrollToPosition(0);
    }

    /**
     * 是否展示空页面
     * @param isCanSub 代表有数据
     */

    private void isShowEmptyView(boolean isCanSub) {
       mVSEmptyView.setVisibility(isCanSub?View.GONE:View.VISIBLE);
       mRvLocationList.setVisibility(isCanSub?View.VISIBLE:View.GONE);
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 设置提交的
     */

    private void setSubState(){
        mTvSure.setTextColor(isCanSub?Color.parseColor(S_CAN_CLICK_COLOR):Color.parseColor(S_NOT_CLICK_COLOR));
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            doSearchSound();
            handled = true;
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            }
        }
        return handled;
    }
}
